package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 38. 外观数列
 * @date 2025/5/8 10:52
 */
public class E38 {

    /**
     * <h3>方法一：动态规划</h3>
     *
     * @param n 第n个数
     * @return 第n个数所表示的字符串
     */
    public String countAndSay1(int n) {
        String[] dp = new String[n + 1];
        dp[1] = "1";
        for (int i = 2; i <= n; i++) {
            StringBuilder builder = new StringBuilder();
            char[] charArray = dp[i - 1].toCharArray();
            char prev = charArray[0];
            int count = 1;
            for (int j = 1; j < charArray.length; j++) {
                if (charArray[j] == prev) {
                    count++;
                } else {
                    builder.append(count).append(prev);
                    count = 1;
                    prev = charArray[j];
                }
            }
            builder.append(count).append(prev);
            dp[i] = builder.toString();
        }
        return dp[n];
    }
}
